from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from bug_manage.forms.wiki import WikiModelForm
from bug_manage import models
from utils.tencent.cos import upload_file_object, settings
from utils.encrypt import uid

"""文档"""


def wiki(request, project_id, ):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id, ):
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 判断用户是否选择父目录
        if form.instance.parent:
            # 如果当前文章有父文章，则深度depth = 父文章深度 + 1，否则 = 1
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})


def wiki_catalog(request, project_id):
    """获取目录"""
    data = models.Wiki.objects.filter(project=project_id).values("id", "title", "parent_id").order_by('depth', 'id')
    return JsonResponse({"status": True, "data": list(data)})


def wiki_delete(request, project_id, wiki_id):
    """删除"""
    url = reverse('wiki', kwargs={'project_id': project_id})
    if wiki_id.isdecimal():
        models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == 'GET':
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        # 判断用户是否选择父目录
        if form.instance.parent:
            # 如果当前文章有父文章，则深度depth = 父文章深度 + 1，否则 = 1
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})


@csrf_exempt
def wiki_upload(request, project_id):
    """markdown上传图片"""
    result = {
        'success': 0,
        'massage': None,
        'url': None,
    }
    # 获取上传的图片
    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['massage'] = '文件不存在'
        return JsonResponse(result)
    # 文件对象上传腾讯对象存储桶中
    bucket = request.tracer.project.bucket
    # 获取图片后缀名,修改图片名称
    ext = image_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone), ext)
    img_url = upload_file_object(bucket=bucket, region=settings.TENCENT_COS_REGION, file_object=image_object,
                                 key=key)
    print(img_url)
    result['success'] = 1
    result['url'] = img_url
    return JsonResponse(result)
